package com.bruce.codeFactory.Thread.designMode.Balking;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

/**
 * @author luotuan
 * @Description
 * @create 2019-03-07 21:58
 **/
public class FileData {
    private final String fileName;
    private String content;
    private boolean changed;

    public FileData(String fileName, String content) {
        this.fileName = fileName;
        this.content = content;
        this.changed = true;
    }

    public synchronized void change(String content) {
        this.content = content;
        this.changed = true;
    }

    public synchronized void save() {
        if (!changed) {
            return;
        }
        doSave();
        this.changed = false;
    }

    private void doSave() {
        System.out.println(Thread.currentThread().getName() + " call do save,content :" + content);
        try (Writer writer = new FileWriter(fileName, true)) {
            writer.write(content);
            writer.write("\n");
            writer.flush();
        } catch (IOException e) {
            System.out.println("保存出现异常："+e.getMessage());
        }
    }
}
